<template>
  <div>
    <!-- <el-input :placeholder="placeholder" :size="size" style="line-hight:40px" v-model="locations.location" class="input-with-select" >
      <el-button slot="append" @click="showSelectDialog" icon="el-icon-location-information"></el-button>
    </el-input> -->
    <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :append-to-body="true"
    :visible.sync="visible">
    <el-row :gutter="15" style="margin-bottom: 5px;">
        <el-col :span="24">
            <el-input id="locationInput" placeholder="请输入内容" @input="searchAutoComplete" v-model="keywords" size="small">
                <template slot="prepend">搜索</template>
            </el-input>
            <div class="search-tips" v-show="tipShow">
              <ul>
                <li v-for="(tip, index) in tips"
                    :key="index"
                    @click="changeTip(tip)"
                    @mouseover="selectedTip=index"
                    :class="{'autocomplete-selected': index === selectedTip}">
                  {{tip.name}}
                  <span style="color: #9ea1a6;font-size: 12px;">{{tip.district}}</span>
                </li>
              </ul>
            </div>
        </el-col>
    </el-row>
    <el-row :gutter="15">
    <el-col :span="24">
        <el-amap vid="amap" :center="center" :zoom="zoom" :events="events" style="width: 100%;height: 600px;">
<!--            <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>-->
            <el-amap-marker v-if="markerPosition.length == 2" vid="component-marker" :position="markerPosition"></el-amap-marker>
        </el-amap>
    </el-col>
    </el-row>
     <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="doSubmit()">确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import { AMapManager } from 'vue-amap'
  export default {
    data () {
      let that = this;
      return {
        loading: false,
        visible: false,
        name: '',
        map: null,
        infoWindow: null,
        selectedTip: -1,
        tipShow: false,
        tips: [],
        center: [120.382665, 36.066938],
        markerPosition: [],
        keywords: '',
        locations: {
            lng: '',
            lat: '',
            location: '',
            province: '',
            city: '',
            district: '',
        },
        searchOption: {

        },
        autoComplete: null,
        zoom: 12,
        events: {
           'click': (e) => {
               that.markerPosition = [e.lnglat.lng, e.lnglat.lat]
               that.locations.lng = String(e.lnglat.lng)
               that.locations.lat = String(e.lnglat.lat)
               let geocoder = new AMap.Geocoder({
                   radius: 1000,
                   extensions: "all"
               });
               geocoder.getAddress([e.lnglat.lng ,e.lnglat.lat], function(status, result) {
                   if (status === 'complete' && result.info === 'OK') {
                       if (result && result.regeocode) {
                        console.log(result)
                           that.locations.location = result.regeocode.formattedAddress
                           that.locations.province = result.regeocode.addressComponent.province
                           that.locations.city = result.regeocode.addressComponent.city
                           that.locations.district = result.regeocode.addressComponent.district
                           if(!result.regeocode.addressComponent.city || result.regeocode.addressComponent.city == '') {
                              that.locations.city = result.regeocode.addressComponent.province
                              that.locations.province = result.regeocode.addressComponent.province.replace('市', '')
                              that.locations.district = result.regeocode.addressComponent.district
                           }
                          that.openInfo(that.locations.lng, that.locations.lat, that.locations.location)
                      }
                   }
               });
           },
          'init': (o) => {
            this.map = o
            let that = this
            AMap.plugin('AMap.Autocomplete', function(){
              // 实例化Autocomplete
              that.autoComplete= new AMap.Autocomplete({input: 'tipinput'})
            })
          }
        }
      }
    },
    components: {
      AMapManager
    },
    props: {
      value: {
        type: String,
        default: () => { return null }
      },
      province: {
        type: String,
        default: () => { return '' }
      },
      city: {
        type: String,
        default: () => { return '' }
      },
      district: {
        type: String,
        default: () => { return '' }
      },
      location: {
        type: String,
        default: () => { return '' }
      },
      lat: {
        type: String,
        default: () => { return '' }
      },
      lng: {
        type: String,
        default: () => { return '' }
      },
      size: {
        type: String,
        default: () => { return 'default' }
      },
      placeholder: {
        type: String,
        default: () => { return '请选择' }
      },
      title: {
        type: String,
        default: () => { return '选择地址' }
      }
    },
    mounted() {

    },
    watch: {
      value: {
        handler (newVal) {
            this.locations.location = newVal
        },
        immediate: true,
        deep: false
      }
    },
    methods: {
      showSelectDialog () {
        this.visible = true
        this.init()
      },
      init (locations) {
        this.visible = true
        this.keywords = ''
        this.markerPosition = []
        this.locations = locations
        if (this.infoWindow != null) {
          this.infoWindow.close()
        } 
        this.$nextTick(() => {
            if(this.locations.lng && this.locations.lat){
                this.markerPosition = [this.locations.lng, this.locations.lat]
                this.center = [this.locations.lng, this.locations.lat]
                this.openInfo(this.locations.lng,this.locations.lat,this.locations.location)
            }
        })
      },
      openInfo(lng,lat,location){
        var info = [];
        info.push("<div>");
        info.push("坐标 : " + lng + "," + lat);
        info.push("地址 :" + location + "</div>");
        this.infoWindow = new AMap.InfoWindow({
          content : info.join("<br/>"),
          offset: new AMap.Pixel(0, -30)
        //使用默认信息窗体框样式，显示信息内容
        });
        this.infoWindow.open(this.map, new AMap.LngLat(lng, lat));
      },
      doSubmit () {
        if(this.locations.lng == '' || this.locations.lat == ''){
          this.$message.warning("请选择地址坐标")
          return 
        }
        this.visible = false
        this.$emit('getValue', this.locations)
      },
      searchAutoComplete() {
        if (!this.keywords || this.keywords.length == 0){
          this.tipShow = false
          return
        }
        this.autoComplete.search(this.keywords, (status, result) => {
          if (status === 'complete') {
            this.tips = result.tips
            this.selectedTip = -1
            if (!this.keywords || this.keywords.length == 0){
              this.tipShow = false
            } else {
              this.tipShow = true
            }
          }
        });
      },
      changeTip(tip) {
        this.tipShow = false
        this.selectedTip = -1
        this.locations.location = tip.name
        let loc = tip.location
        let that = this
        if(loc && loc.length !== ''){
          this.markerPosition = [loc.lng, loc.lat]
          this.center = [loc.lng, loc.lat]
          this.locations.lng = String(loc.lng)
          this.locations.lat = String(loc.lat)
          this.zoom = 18
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([loc.lng ,loc.lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                that.locations.location = result.regeocode.formattedAddress
                that.locations.province = result.regeocode.addressComponent.province
                that.locations.city = result.regeocode.addressComponent.city
                that.locations.district = result.regeocode.addressComponent.district
                if(!result.regeocode.addressComponent.city || result.regeocode.addressComponent.city == '') {
                  that.locations.city = result.regeocode.addressComponent.province
                  that.locations.province = result.regeocode.addressComponent.province.replace('市', '')
                  that.locations.district = result.regeocode.addressComponent.district
                }
                that.openInfo(loc.lng, loc.lat, that.locations.location)
              }
            }
          });
        }
      }
    }
  }
</script>

<style lang="less" scoped>
.search-tips {
    position: absolute;
    left: 100px;
    z-index: 999;
    border: 1px solid #dbdbdb;
    background: #FFF;
    overflow: auto;
    ul {
      padding: 0;
      margin: 0;

        li {
          height: 40px;
          line-height: 40px;
          box-shadow: 0 1px 1px rgba(0,0,0,.1);
          padding: 0 10px;
          cursor: pointer;

        &.autocomplete-selected {
           background: #eee;
         }
        }
    }
}
</style>
